package com.tim.app.ui.activity.found;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.HorizontalDividerItemDecoration;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.server.api.API_Discover;
import com.tim.app.server.entry.SelectInfo;
import com.tim.app.server.entry.Special;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.SpecialDataListResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.MainActivity;
import com.tim.app.ui.adapter.selceted.SelectedInfoItemAdapter;
import com.tim.app.ui.view.AnswerHeadView;
import com.tim.app.ui.view.SpecialDetialHeadView;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.ArrayList;
import java.util.List;


/**
 * 专题详情页
 */
public class SpecialDetailActivity extends BaseActivity implements LoadMoreHandler, BaseRecyclerAdapter.OnItemClickListener {

    public static final String TAG = "SpecialDetailActivity";

    private AppBarLayout appbar;
    private ImageView ivBack, ivReport;
    private TextView tvTitle;
    private TextView tvSpecialName;
    private View vLine;
    private ImageView ivSpecialBg;


    private Special special;
    private boolean isFromPush = false;

    private LoadMoreRecycleViewContainer load_more;

    private WrapRecyclerView wrvSpecial;
    private SelectedInfoItemAdapter adapter;
    private List<SelectInfo> dataList;

    private SpecialDetialHeadView headView;

    public static void start(Context context, Special special, boolean isFromPush) {
        Intent intent = new Intent(context, SpecialDetailActivity.class);
        intent.putExtra("special", special);
        intent.putExtra(AppKey.IS_FROM_PUSH, isFromPush);
        if (isFromPush) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_special_detail;
    }


    @Override
    public void initView() {
        appbar = (AppBarLayout) findViewById(R.id.appbar);
        ivBack = (ImageView) findViewById(R.id.ivBack);
        ivReport = (ImageView) findViewById(R.id.ivReport);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvSpecialName = (TextView) findViewById(R.id.tvSpecialName);
        ivSpecialBg = (ImageView) findViewById(R.id.ivSpecialBg);
        vLine = findViewById(R.id.vLine);

        ivBack.setOnClickListener(this);
        ivReport.setOnClickListener(this);

        special = (Special) getIntent().getSerializableExtra("special");
        isFromPush = getIntent().getBooleanExtra(AppKey.IS_FROM_PUSH, false);


        load_more = (LoadMoreRecycleViewContainer) findViewById(R.id.load_more);
        wrvSpecial = (WrapRecyclerView) findViewById(R.id.wrvSpecial);

        wrvSpecial.setOverScrollMode(View.OVER_SCROLL_NEVER);

        load_more.useDefaultFooter(View.GONE);
        load_more.setAutoLoadMore(true);
        load_more.setLoadMoreHandler(this);

        if (dataList == null) {
            dataList = new ArrayList<>();
        }

        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        wrvSpecial.setLayoutManager(layoutManager);

        wrvSpecial.setHasFixedSize(true);
        wrvSpecial.setNestedScrollingEnabled(false);
        adapter = new SelectedInfoItemAdapter(this, dataList);

        headView = (SpecialDetialHeadView) LayoutInflater.from(this).inflate(R.layout.special_detail_head_view, null);
        wrvSpecial.addHeaderView(headView);
        wrvSpecial.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).color(getResources().getColor(R.color.view_background_color)).size((int) getResources().getDimension(R.dimen.dimen_5)).build());

        adapter.setOnItemClickListener(this);
        wrvSpecial.setAdapter(adapter);

        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset == 0) {  //展开状态
                    ivBack.setImageResource(R.drawable.ic_back_white);
                    ivReport.setImageResource(R.drawable.ic_more_white);
                    tvTitle.setVisibility(View.GONE);
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    vLine.setVisibility(View.VISIBLE);
                    ivBack.setImageResource(R.drawable.ic_back_black);
                    ivReport.setImageResource(R.drawable.ic_more);
                    tvTitle.setVisibility(View.VISIBLE);
                } else {//中间状态
                    vLine.setVisibility(View.GONE);
                    tvTitle.setVisibility(View.GONE);
                }

                int maxScroll = appBarLayout.getTotalScrollRange();
                float percentage = (float) Math.abs(verticalOffset) / (float) maxScroll;
                if (percentage > 0.7f) {
                    tvTitle.setVisibility(View.VISIBLE);
                    ivBack.setImageResource(R.drawable.ic_back_black);
                } else {
                    tvTitle.setVisibility(View.GONE);
                    ivBack.setImageResource(R.drawable.ic_back_white);
                }
            }
        });

        refreshUi(special);

    }


    @Override
    public void initData() {
        pageNum = 1;
        API_Discover.ins().getSpecialDataList(TAG, special.getId(), pageNum, AppKey.PAGE_SIZE, refreshCallback);
    }

    private int pageNum = 1;


    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        API_Discover.ins().getSpecialDataList(TAG, special.getId(), pageNum + 1, AppKey.PAGE_SIZE, moreCallback);
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        if (null == dataList || position > dataList.size() - 1)
            return;
        SelectInfo info = dataList.get(position);
        ViewGT.gotoDetailActivity(this, info);
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errcode, String errMsg, int id, boolean fromcache) {
            if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                if (dataList != null) {
                    dataList.clear();
                }
                SpecialDataListResult result = new Gson().fromJson(resultValue, SpecialDataListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getHashmap() && null != result.getRes().getHashmap().getInfoPage()) {
                    if (null != result.getRes().getHashmap().getInfoPage().getResult()) {
                        dataList.addAll(result.getRes().getHashmap().getInfoPage().getResult());
                        adapter.notifyDataSetChanged();
                        special = result.getRes().getHashmap().getSpecialTopic();
                        refreshUi(special);
                    }
                    pageNum = result.getRes().getHashmap().getInfoPage().getCurrentPageNo();
                    if (pageNum != result.getRes().getHashmap().getInfoPage().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                }

            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errcode, String errMsg, int id, boolean fromcache) {
            if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                SpecialDataListResult result = new Gson().fromJson(resultValue, SpecialDataListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getHashmap() && null != result.getRes().getHashmap().getInfoPage()) {
                    if (null != result.getRes().getHashmap().getInfoPage().getResult()) {
                        dataList.addAll(result.getRes().getHashmap().getInfoPage().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    pageNum = result.getRes().getHashmap().getInfoPage().getCurrentPageNo();
                    if (pageNum != result.getRes().getHashmap().getInfoPage().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                }
            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };


    private void refreshUi(Special special) {
        if (null != special) {
            if (!TextUtils.isEmpty(special.getName())) {
                tvSpecialName.setText("#" + special.getName() + "#");
                tvTitle.setText("#" + special.getName() + "#");
            }
            headView.setData(special);
            BitmapLoader.ins().loadImage(special.getImage(), ivSpecialBg);

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (isFromPush) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack://返回
                finish();
                break;
        }
    }

}
